package com.luis.toolbox.outbound;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
@ConditionalOnProperty(prefix="outbound",name = "destination", havingValue = "http")
public class HttpProducer {

	private final Logger log = LoggerFactory.getLogger(HttpProducer.class);
	private WebClient webClient;

	@Value("${http.baseurl:''}")
	private String baseUrl;

	@Value("${http.api-path:''}")
	private String api;

	@ServiceActivator(inputChannel = "httpOutboundChannel")
	@Bean
	public MessageHandler httpOutbound(WebClient.Builder webClientBuilder) {
		if(this.webClient == null){
			this.webClient = webClientBuilder.baseUrl(baseUrl).build();
		}
		/* a common influxdb2.0 write request
		curl --request POST \
		"http://localhost:8086/api/v2/write?org=YOUR_ORG&bucket=YOUR_BUCKET&precision=ns" \
		--header "Authorization: Token YOUR_API_TOKEN" \
		--header "Content-Encoding: gzip" \
		--header "Content-Type: text/plain; charset=utf-8" \
		--header "Accept: application/json" \
		--data-binary @air-sensors.gzip
		*/

		return message -> this.webClient.post().uri(api)
				.bodyValue(message.getPayload().toString())
				.retrieve().bodyToMono(String.class).subscribe();
	}


}
